package org.yys.demo;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.yys.constant.MqConstant;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class BatchDemo {


    public void batchProducer() throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        // 创建生产者
        DefaultMQProducer producer = new DefaultMQProducer("batch-producer-group");
        producer.setNamesrvAddr(MqConstant.NAMESRV_ADDR);
        producer.start();

        // 创建消息

        Message message1 = new Message("batch-topic", "这是一个简单的消息1".getBytes());
        Message message2 = new Message("batch-topic", "这是一个简单的消息2".getBytes());
        Message message3 = new Message("batch-topic", "这是一个简单的消息3".getBytes());

        // 发送消息
        SendResult send = producer.send(Arrays.asList(message1,message2,message3));
        System.out.println("result:"+send);


        producer.shutdown();

    }

    public void batchConsumer() throws MQClientException, InterruptedException, IOException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("batch-consumer-group");
        consumer.setNamesrvAddr(MqConstant.NAMESRV_ADDR);
        consumer.subscribe("batch-topic","*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                System.out.println("消费者接收消息..."+list.size());
                System.out.println("message:"+list.get(0));
                System.out.println("context:"+consumeConcurrentlyContext);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();


        // 线程睡100s. 注:由于监听器在另一个线程中, 不会被当前线程的sleep影响.
        System.in.read();

    }

}
